import sys
from DrissionPage import ChromiumPage, ChromiumOptions
from tqdm import tqdm
import logging
import time

log_file = 'download_log.txt'
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(message)s', encoding='utf-8',
                    datefmt='%Y-%m-%d %H:%M:%S')


def get_file(shop_name, url):
    logging.info(f"登录网站{url}")
    driver.get(url)
    driver.wait(1)
    results = driver.ele('.flex align-items-center date-select').eles('.el-radio-button el-radio-button--mini')
    driver.wait(0.5)
    try:
        if driver.ele('.com-box service-box collapsed'):
            pass
        else:
            driver.ele('.collapse-handle').click()
            driver.wait(0.5)
    except:
        driver.ele('.collapse-handle').click()
        driver.wait(0.5)
    for result in results:
        if result.text == '昨日':
            result.click()
            driver.wait(2)
            driver.ele('.export-btn').click()
            driver.wait(4)
            driver.ele('.el-button el-button--primary el-button--medium').click()
            driver.wait(5)
            logging.info(f'{shop_name}的数据下载完毕')
            break


def get_cmm_file():
    global driver
    co = ChromiumOptions()
    driver = ChromiumPage(co)
    try:
        driver.get('https://www.chanmama.com/login.html')
        driver.eles('.el-checkbox__inner')[1].click()
        driver.wait(0.5)
        driver.ele('.el-button el-button--primary').click()
        driver.wait(1)
    except:
        pass
    try:
        with open('店铺链接.txt', encoding='utf-8') as f:
            for line in tqdm(f.readlines()):
                line = line.strip()
                if not line:  # 如果是空白行，跳过
                    continue
                shop_name = line.split(':')[0]
                logging.info(f'开始{shop_name}的数据下载')
                url = line.split(':', 1)[1].strip()
                try:
                    get_file(shop_name=shop_name, url=url)
                except:
                    logging.info(f'shop_name={shop_name}, url={url}出现问题,正在重试')
                    time.sleep(2)
                    try:
                        driver.get('https://www.chanmama.com/login.html')
                        driver.eles('.el-checkbox__inner')[1].click()
                        driver.wait(0.5)
                        driver.ele('.el-button el-button--primary').click()
                        driver.wait(1)
                    except:
                        try:
                            get_file(shop_name=shop_name, url=url)
                        except:
                            driver.wait(15)
                            get_file(shop_name=shop_name, url=url)
    except Exception as e:
        logging.info(e)
        pass
    finally:
        driver.wait(15)
        logging.info('程序结束')
        driver.quit()


if __name__ == '__main__':
    get_cmm_file()
    logging.info('文件下载完毕,检查数量是否为23个,接下来将数据录入数据库,本程序结束,')
